package com;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;

/*使用配置类  不使用配置文件（applicationContext.xml）*/
@Configuration
@ComponentScan("com.itbaizhan") //扫描包
//@EnableAspectJAutoProxy  ////代替xml中AOP注解
//配置类代替xml中的注解事务支持：在配置类上方写@EnableTranscationManagement
@EnableTransactionManagement
public class SpringConfig {

    //配置dataSource 创建SqlSessionFactory对象与创建MapperScannerConfigurer对象
    //在容器中创建 所以@Bean
    @Bean
    public DataSource getDataSource(){
        //创建数据源对象
        DruidDataSource druidDataSource = new DruidDataSource();
        //配置数据
        druidDataSource.setDriverClassName("com.mysql.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("hua8503176");
        return druidDataSource;
    }

    //把上面的dataSource传进来
    @Bean
    public SqlSessionFactoryBean getSqlSession(DataSource dataSource){
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }

    @Bean
    public MapperScannerConfigurer getMapperScanner(){
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.itbaizhan.dao");
        return mapperScannerConfigurer;
    }

    @Bean
    public DataSourceTransactionManager getTransactionManage(DataSource dataSource){
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource);
        return dataSourceTransactionManager;
    }
}
